# =======================================
# ColoredFormatter v0.1b - Copyright 2013
# Writted by muttley
# =======================================

import re
import logging

# variable to import/inizializze when use "from utils.coloredlogger import *"
__all__ = ['coloredFormatter','logging', 'BLACK', 'RED', 'GREEN', 'YELLOW', 'BLUE', 'MAGENTA', 'CYAN', 'WHITE' ]

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)

RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"

class coloredFormatter(logging.Formatter):
    FORMAT = "[$BOLD%(name)-20s$RESET][%(levelname)-18s]  %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"
    colors = {
        'WARNING': YELLOW,
        'INFO': WHITE,
        'DEBUG': BLUE,
        'CRITICAL': YELLOW,
        'ERROR': RED
        }
    
    def __init__(self, msg = None, use_color = True, datefmt=None):
        if msg is None: 
            msg = self.FORMAT
        else: 
            msg = self.__formatterMessage(msg, use_color)
        
        self.use_color = use_color
        
        super().__init__(msg, datefmt)

    def format(self, record):
        levelname = record.levelname
        if self.use_color and levelname in self.colors:
            record.levelname = COLOR_SEQ % (30 + self.colors[levelname]) + levelname + RESET_SEQ
        else:
            record.levelname = self.__formatterMessage(record.levelname, self.use_color)
        
        return super().format(record)
    
    def __formatterMessage(self, message, use_color = True):
        if use_color:
            message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
        else:
            message = message.replace("$RESET", "").replace("$BOLD", "")
            message = re.sub(r'\033[1;[0-9]+m', "", message)
        return message
    
    def setColors(self, colors):
        self.colors = colors

# EXAMPLE OF USING
#if __name__ == "__main__":
#    
#    # root logger
#    logger = logging.getLogger('myAppNameLogPath')
#    # verbosity of root to send to handler
#    logger.setLevel(logging.DEBUG)
#    
#    # create file handler which logs even DEBUG messages
#    fh = logging.FileHandler('spam.log', 'a')
#    fh.setLevel(logging.DEBUG)
#   
#    # create console handler which logs even WARNING messages
#    ch = logging.StreamHandler()
#    ch.setLevel(logging.WARNING)
#    
#    # create formatter with color (attributes: http://docs.python.org/2/library/logging.html#logrecord-attributes)
#    formatter = coloredFormatter("[$BOLD%(name)-25s$RESET][%(levelname)-20s] !COLORED!  %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)")
#    ch.setFormatter(formatter)
#    
#    # create same formatter but without color
#    formatterFile = coloredFormatter("[$BOLD%(name)-25s$RESET][%(levelname)-10s] !NO-COLORED! %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)", False)
#    fh.setFormatter(formatterFile)
#    
#    # add the handlers to logger
#    logger.addHandler(ch)
#    logger.addHandler(fh)
#    
#    # create a sub logger of root
#    logger1 = logging.getLogger('myAppNameLogPath.area1')
#    
#    # example of loggin
#    logger.debug('debug message')
#    logger.info('info message')
#    logger.warn('warn message')
#    logger.error('error message')
#    logger.critical('critical message')
#    logger1.debug('Quick zephyrs blow, vexing daft Jim.')
#    logger1.info('How quickly daft jumping zebras vex.')
 
